/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shellCommands;

import Sessions.EcomAdminRemote;
import Sessions.EcomCustomersRemote;
import entityBeans.Productsstore;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author SOGOBA
 */
public class StoreCommand implements InterShell{
    ContextCommande cxtCmd;
    public StoreCommand(ContextCommande ContextCommand){
          cxtCmd =  ContextCommand;
    }

    @Override
    public Commands getName() {
          return Commands.store;
    }

    @Override
    public String getShortDescription() {
        String description = "Store Management\n";
            description += "\t  : without argument ............................................ list all stores\n";
            description += "\t  : -add [nameStore] [Accout] [solde] [adress].................create a store\n";
            description += "\t  : -remove [Store ID]...........................................delete a store\n";
        return description;    }

    @Override
    @SuppressWarnings("ConvertToStringSwitch")
    public void execute(String cmd,EcomAdminRemote ecomAdmin,EcomCustomersRemote ecomCust) throws Exception {
   
        StringTokenizer st = new StringTokenizer(cmd, " ");

        // Ignore cmd
        st.nextToken();

        // sans argument, on liste les magasins
        if (st.countTokens() == 0) {
            List<Productsstore> lesStores = ecomCust.getStores();
           if (cxtCmd.getVar("output").toString().equals("XML")){
            System.out.println(getXML(lesStores));
            }
            else{
                 System.out.println(getText(lesStores));
                }
        } // prise en compte des arguments
        else {
            String option = st.nextToken();

            // adding
            if (option.equals("-add")) {            
                if (st.countTokens() >= 4) {
                   String nameStore= st.nextToken();
                   String cmp=st.nextToken();
                   Double solde=Double.valueOf(st.nextToken());
                   String adress="";
                   while (st.hasMoreElements()){
                    adress+=st.nextToken();
                   }
                   //ajout du store en base
                   ecomAdmin.createStore(nameStore, cmp, solde, adress);
                   System.out.println("Your store was successfully created ");
                } else {
                    System.out.println("Command is not avalaible");
                }

            } // delete a store
            else if (option.equals("-remove")) {
                if (st.countTokens() == 1) {
                        Integer storeId;
                        storeId = Integer.valueOf(st.nextToken());
                        ecomAdmin.removeStore(storeId);
                        System.out.println("Your store was successfully removed ");      
                } else {
                    System.out.println("Command is not avalaible");
                }
            }
             } 
        
    }
    
         

    @SuppressWarnings("CallToThreadDumpStack")
public String getXML(List<Productsstore> lesStores){
        String xmlString="";
        try {
            // Create Document factory
            DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
            // Create document
            DocumentBuilder constructeur = fabrique.newDocumentBuilder();
            // Read a file XML with DOM
            File xml = new File("C:/Users/SOGOBA/Documents/NetBeansProjects/StoreEcom/StoreEcom-app-client/src/java/storeecom/XMLDocument.xml");
            Document document = constructeur.parse(xml);
            // Creation de l'arborescence du DOM
            Element racine = document.getDocumentElement();
           racine.appendChild(document.createComment("Dysplay all stores "));
            Element stores = document.createElement("stores");
            racine.appendChild(stores);
            // Get all products
            for (Productsstore store : lesStores) {
                Element s = document.createElement("store");
                stores.appendChild(s);
                Element storeId = document.createElement("reference");
                storeId.setTextContent(store.getReferenceStore().toString());
                s.appendChild(storeId);
                Element name = document.createElement("name_store");
                name.setTextContent(store.getName());
                s.appendChild(name);
                Element adrss = document.createElement("adress");
                adrss.setTextContent(store.getAdress());
                s.appendChild(adrss);
            }
                DOMSource domSource = new DOMSource(document);
                StringWriter writer = new StringWriter();
                StreamResult result = new StreamResult(writer);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.transform(domSource, result);
                xmlString = writer.toString();
        }
        catch (IOException | ParserConfigurationException ex) {
            Logger.getLogger(CustomersCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    catch(Exception e){
            e.printStackTrace();
          }
    return xmlString;
}


public String getText (List<Productsstore> lesStores){
    String textString="List of all stores \n";
    for (Productsstore store : lesStores){
       textString+="reference : "+ store.getReferenceStore() +"name : "+ store.getName()+ "adress : "+ store.getAdress()+ "\n";
    }
    return textString;
}

}
